package com.dage.salesflow.service;

import com.alibaba.excel.util.ListUtils;
import com.dage.salesflow.kit.Ret;
import com.dage.salesflow.kit.TreeKit;
import com.dage.salesflow.model.Dict;
import com.dage.salesflow.model.vo.TreeModel;
import com.dage.salesflow.validation.DelForeignInfo;
import com.dage.salesflow.validation.ValidationKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import io.jboot.aop.annotation.Bean;
import io.jboot.db.model.Columns;
import io.jboot.service.JbootServiceBase;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Bean
public class DictService extends JbootServiceBase<Dict> {

	/**
	 * 字典管理分页
	 *
	 * @param key
	 * @param value
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public Page<Dict> listByPage(String key, String value, Integer pid, int pageNum, int pageSize) {
		String sqlSelect = "SELECT id,dic_key,dic_value,dict_order";
		String sql = "FROM `t_dict` WHERE 1=1";
		List<Object> paras = new ArrayList<>();
		if (StrKit.notBlank(key)) {
			sql += " AND dic_key like ?";
			paras.add("%" + key + "%");
		}
		if (StrKit.notBlank(value)) {
			sql += " AND dic_value like ?";
			paras.add("%" + value + "%");
		}
		if (pid != null && pid > 0) {
			sql += " AND parent_id = ?";
			paras.add(pid);
		} else {
			sql += " AND (parent_id IS NULL OR parent_id=0)";
		}
		sql += " ORDER BY dict_order";
		return DAO.paginate(pageNum, pageSize, sqlSelect, sql, paras.toArray());
	}

	/**
	 * 树形列表
	 */
	public List list(String key, String value, Integer pid) {
		List<Dict> dictList = TreeKit.getChildNodes(pid, (Dict) DAO);
		dictList = dictList.stream().filter(dict -> {
			boolean flag = true;
			if (StrKit.notBlank(key)) {
				flag = flag && dict.getDicKey().contains(key);
			}
			if (StrKit.notBlank(value)) {
				flag = flag && dict.getDicValue().contains(value);
			}
			return flag;
		}).collect(Collectors.toList());
		List<? extends TreeModel> list = TreeKit.appendParentNodes(dictList);
		List<TreeModel> roots = ListUtils.newArrayList();
		for (TreeModel model : list) {
			if (model.getParentId() == null || model.getParentId() == 0) {
				roots.add(model);
			}
		}
		list.removeAll(roots);
		return list;
	}

	/**
	 * 根据key查询
	 *
	 * @param key
	 * @return
	 */
	public List<Dict> listByKey(String key) {
		String sql = "SELECT id,parent_id,dic_key,dic_value,dict_order FROM `t_dict` WHERE 1=1";
		List<Object> paras = new ArrayList<>();
		if (StrKit.notBlank(key)) {
			sql += " AND dic_key = ?";
			paras.add(key);
		}
		sql += " ORDER BY dict_order";
		return DAO.find(sql, paras.toArray());
	}

	/**
	 * 根据pid查询
	 */
	public List<Dict> listByPid(int pid) {
		return DAO.find("SELECT id,dic_key,dic_value,dict_order FROM `t_dict` WHERE parent_id=? ORDER BY dict_order", pid);
	}

	/**
	 * 根据keys查询
	 *
	 * @param keys
	 * @return
	 */
	public Map<String, List<Dict>> listByKeys(String keys) {
		String[] keyArr = keys.split(",");
		Kv data = Kv.create();
		for (String key : keyArr) {
			data.set(key, DAO.find("SELECT id,dic_key,dic_value FROM `t_dict` WHERE dic_key = ? ORDER BY dict_order", key));
		}
		return data;
	}

	/**
	 * 根据value查询
	 *
	 * @param value
	 * @return
	 */
	public Dict findByValue(String value) {
		return findFirstByColumns(Columns.create("dic_value", value));
	}

	public Ret del(int id) {
		Set<DelForeignInfo> delForeignInfo = ValidationKit.getDelForeignInfo(Dict.class);
		for (DelForeignInfo info : delForeignInfo) {
			long num = Db.queryLong(info.sql, id);
			if (num > 0) {
				return Ret.err("有" + num + "条关联的" + info.name + "数据，删除失败！");
			}
		}
		if (deleteById(id)) {
			return Ret.ok();
		} else {
			return Ret.err("删除失败");
		}
	}
}